/**
 * 
 */
package com.cwnuzj.ffms.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;

import com.cwnuzj.ffms.model.navigation.Category;
import com.cwnuzj.ffms.model.navigation.TreeNodeObject;
import com.cwnuzj.ffms.ui.editor.AccountBookInput;
import com.cwnuzj.ffms.ui.editor.AccountBookEditor;
import com.cwnuzj.ffms.ui.view.navigation.NavigationView;

/**
 * @author jeff.zheng
 * 
 */
public class OpenAccountBookEditor extends AbstractHandler {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.
	 * ExecutionEvent)
	 */
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {

		// Get the view
		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
		IWorkbenchPage page = window.getActivePage();
		NavigationView view = (NavigationView) page.findView(NavigationView.ID);
		// Get the selection
		ISelection selection = view.getSite().getSelectionProvider().getSelection();
		if (selection != null && selection instanceof IStructuredSelection) {
			Object obj = ((IStructuredSelection) selection).getFirstElement();
			
			// If we had a selection lets open the editor
			if (obj != null) {
				TreeNodeObject node = (TreeNodeObject) obj;
				AccountBookInput input = new AccountBookInput(node.getName());
				try {
					page.openEditor(input, AccountBookEditor.ID);

				} catch (PartInitException e) {
					throw new RuntimeException(e);
				}
			} else {
				AccountBookInput input = new AccountBookInput("no selection");
				try {
					page.openEditor(input, AccountBookEditor.ID);

				} catch (PartInitException e) {
					throw new RuntimeException(e);
				}
			}
		}
		return null;

	}

}
